﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using l1cs.server.templates;
using l1cs.server.utils;
using l1cs.server.datatables;

namespace l1cs.server.command
{
    public class L1Commands
    {
        private static Logger _log = Logger.getLogger( typeof( L1Commands ).FullName );

        private static L1Command fromResultSet( DataRow rs )
        {
            return new L1Command( Convert.ToString( rs["name"] ), SqlUtils.toInt( rs["access_level"] ),
                    Convert.ToString( rs["class_name"] ) );
        }

        public static L1Command get( String name )
        {
            /*
             * デバッグやテスト容易性の為に毎回DBに読みに行きます。 キャッシュするより理論上パフォーマンスは下がりますが、無視できる範囲です。
             */
            String sqlstr = "SELECT * FROM commands WHERE name=?1";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.String ).Value = name;
                foreach ( DataRow item in wrapper.GetDataTable( cmd ).Rows )
                {
                    return fromResultSet( item );
                }
            }
            return null;
        }

        public static List<L1Command> availableCommandList( int accessLevel )
        {
            List<L1Command> result;
            String sqlstr = "SELECT * FROM commands WHERE access_level <= ?1";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd = new MySqlCommand( sqlstr );
                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = accessLevel;
                MySqlDataAdapter da = new MySqlDataAdapter( cmd );
                result = new List<L1Command>();
                foreach ( DataRow item in wrapper.GetDataTable( cmd ).Rows )
                {
                    result.Add( fromResultSet( item ) );
                }
            }
            return result;
        }
    }
}
